package service

import (
	"fmt"
	"multimedia/conf"
	"multimedia/utils"
	"strconv"
	"strings"
	"time"

	"github.com/fiorix/go-eventsocket/eventsocket"
	uuid "github.com/satori/go.uuid"
	log "github.com/sirupsen/logrus"
)

func (s *Srv) ProcessEvent() {
	defer utils.HandlePanic()
	log.WithField("Func", "ProcessEvent").Warnf("start processEvent")
	for ev := range s.fsEvent.EventChan {
		evname := ev.Get("Event-Name")
		switch evname {
		case "CHANNEL_ANSWER":
			s.ProcessEnterConf(ev)
		case "CHANNEL_HANGUP":
			s.ProcessExit(ev)
		case "CUSTOM":
			s.ProcessCusTom(ev)
		}
	}
}

func (s *Srv) ProcessCusTom(ev *eventsocket.Event) {
	subname := ev.Get("Event-Subclass")
	if subname != "conference::maintenance" {
		return
	}
	conferName := ev.Get("Conference-Name")

	action := ev.Get("Action")

	if conferName == "" {
		return
	}
	if action == "start-recording" {
		path := ev.Get("Path")
		res := strings.Split(path, "/")
		s.mysql.UpdateConferRecordFlag(conferName)
		p := fmt.Sprintf("%s/%s", "/record_files", res[len(res)-1])
		s.RecordStart(conferName, p)
		log.WithField("Func", "ProcessCusTom").Warnf("start-recording the confer is:%s,%s", conferName, p)
	} else if action == "stop-recording" {
		err, roomInfo := s.mysql.GetRoomInfoByAppIdAndRoomId(conf.ConfigFile.SdkAppId, conferName)
		if err != nil {
			log.WithField("Func", "ProcessExit").Warnf("room not find %s,%d,%v", conferName, conf.ConfigFile.SdkAppId, err)
			return
		}
		path := ev.Get("Path")
		res := strings.Split(path, "/")
		log.WithField("Func", "ProcessCusTom").Warnf("stop record the confer is:%s,%v,%s", conferName, res, path)
		if len(res) > 2 {
			p := fmt.Sprintf("%s/%s", "/record_files", res[len(res)-1])
			s.mysql.UpdateRecord(roomInfo.Id, p, "", roomInfo.Record)
			s.wsClient.NotifyRecEnded(roomInfo.Id, roomInfo.RoomId)
		} else {
			log.WithField("Func", "ProcessCusTom").Errorf("stop record path error :%s,%v,%s", conferName, res, path)
		}
		s.RecordStop(conferName)
	}
}
func (s *Srv) ProcessExit(ev *eventsocket.Event) {
	proto := ev.Get("Variable_chat_proto")

	if proto != "verto" {
		return
	}

	roomId := ev.Get("Caller-Callee-Id-Number")
	phone_no := ev.Get("Caller-Ani")

	err, roomInfo := s.mysql.GetRoomInfoByAppIdAndRoomId(conf.ConfigFile.SdkAppId, roomId)
	if err != nil {
		log.WithField("Func", "ProcessExit").Warnf("room not find %s,%d,%v", roomId, conf.ConfigFile.SdkAppId, err)
		return
	}
	user := s.mysql.GetUserInfoByPhone(phone_no)
	if user == nil {
		log.WithField("Func", "ProcessEnterConf").Errorf("the user is not find %d", phone_no)
		return
	}
	timestamp := ev.Get("Event-Date-Timestamp")
	currtime, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil {
		currtime = time.Now().UnixMicro()
	}
	memName := fmt.Sprintf("%d", user.Id)
	s.mysql.UpdateUserExitRoomPlayTime(roomInfo.Id, memName, currtime)
	log.WithField("Func", "MediaCallBack").Warnf("exit meeting %d the roomid is:%d the member is:%s",
		roomInfo.Id, roomInfo.RoomId, memName)

}

func (s *Srv) ProcessEnterConf(ev *eventsocket.Event) {
	proto := ev.Get("Variable_chat_proto")
	if proto != "verto" {
		return
	}
	timeStamp := ev.Get("Event-Date-Timestamp")
	enterRoomTime, err := strconv.ParseInt(timeStamp, 10, 64)
	if err != nil {
		enterRoomTime = time.Now().UnixMicro()
	}
	conferId := ev.Get("Caller-Callee-Id-Number")
	userNum := ev.Get("Caller-Ani")
	user := s.mysql.GetUserInfoByPhone(userNum)
	if user == nil {
		log.WithField("Func", "ProcessEnterConf").Errorf("the user is not find %d", userNum)
		return
	}
	evtData := utils.EvtDataReq{}
	evtData.MemName = fmt.Sprintf("%d", user.Id)

	roomInfo := s.mysql.NewGetRoomInfoByRoomId(conferId)
	if *roomInfo == (utils.RoomInfo{}) {
		con := s.mysql.GetConfeByRoomId(conferId)
		confer := utils.RoomInfoCreate{
			AppId:     conf.ConfigFile.SdkAppId,
			Uuid:      uuid.NewV4().String(),
			RoomId:    conferId,
			ConfrId:   conferId,
			RoomType:  "Vedio",
			ConfrType: "Imme",
			Creator:   fmt.Sprintf("%d", con.Creator),
			Password:  "",
			State:     0,
		}
		id := s.mysql.CreateRoomInfo(&confer)
		roomInfo.ConfId = conferId
		roomInfo.Id = id
		roomInfo.Password = ""
		s.mysql.UpdateRoomInfoStatus(roomInfo.Id, utils.CREATED, 0, conferId)
		log.WithField("Func", "ProcessEnterConf").Warnf("Create meeting %d the roomid is:%d", roomInfo.Id, conferId)
	} else {
		s.mysql.UpdateRoomInfoStatus(roomInfo.Id, utils.CREATED, 0, conferId)
	}
	conf := utils.EmediaRoomInfo{
		AppId:    conf.ConfigFile.SdkAppId,
		Id:       roomInfo.Id,
		ConfrId:  roomInfo.ConfId,
		Password: roomInfo.Password,
	}
	s.mysql.InsertRoomPlayUser(&conf, &evtData, enterRoomTime)
	log.WithField("Func", "ProcessEnterConf").Warnf("enter meeting %d the roomid is:%s the member is:%s",
		roomInfo.Id, conf.ConfrId, evtData.MemName)
}
